<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="productIds">
        <el-select v-model="queryParams.productIds" multiple placeholder="请选择项目">
          <el-option
            v-for="item in productOptions"
            :key="item.id"
            :label="item.productName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排期日期" prop="schedulesTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.schedulesTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择排期日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="推送状态" prop="pushState">
        <el-select v-model="queryParams.pushState" placeholder="请选择推送状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.push_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['projects:schedules:export']"
        >导出排期记录</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schedulesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="sId" />
      <el-table-column label="用户" align="center" prop="customerName" />
      <el-table-column label="项目" align="center" prop="productNames" />
      <el-table-column label="间隔时间" align="center" prop="intervalDays" />
      <el-table-column label="排期日期" align="center" prop="schedulesTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.schedulesTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否推送" align="center" prop="pushState" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.pushState === 1">已推送</span>
          <span v-else>未推送</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['projects:schedules:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listSchedules, getSchedules, delSchedules, addSchedules, updateSchedules } from "@/api/projects/schedules";
import CustomerSelect from "@/views/projects/SlCustomInfo/select.vue";
import {getProductOptions} from "@/api/projects/SlApointForm";


export default {
  name: "Schedules",
  components: {CustomerSelect,'pagination': () => import('@/components/Pagination')},
  dicts: ['push_state'],
  data() {
    return {
      productOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员排期表格数据
      schedulesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customId: null,
        productIds: null,
        schedulesTime: null,
        pushState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    // 获取产品选项（优先从缓存获取）
    this.getProducts();
    this.getList();
  },
  methods: {
    /** 查询会员排期列表 */
    getList() {
      this.loading = true;
      listSchedules(this.queryParams).then(response => {
        this.schedulesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sId: null,
        customId: null,
        productIds: null,
        schedulesTime: null,
        pushState: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        intervalTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员排期";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sId = row.sId || this.ids
      getSchedules(sId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会员排期";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sId != null) {
            updateSchedules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSchedules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sIds = row.sId || this.ids;
      this.$modal.confirm('是否确认删除会员排期编号为"' + sIds + '"的数据项？').then(function() {
        return delSchedules(sIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('projects/schedules/export', {
        ...this.queryParams
      }, `schedules_${new Date().getTime()}.xlsx`)
    },

    // 获取产品选项
    async getProducts() {
      try {
        // 获取缓存和缓存时间
        const cachedData = localStorage.getItem('productOptionsData');
        if (cachedData) {
          const { data, timestamp } = JSON.parse(cachedData);
          // 检查缓存是否在24小时内
          if (Date.now() - timestamp < 24 * 60 * 60 * 1000) {
            this.productOptions = data;
            return;
          }
        }

        // 缓存过期或不存在，请求新数据
        const res = await getProductOptions();
        if (res.code === 200) {
          this.productOptions = res.data;
          // 存入缓存，带时间戳
          localStorage.setItem('productOptionsData', JSON.stringify({
            data: res.data,
            timestamp: Date.now()
          }));
        } else {
          this.$modal.msgError(res.msg || '获取产品选项失败');
        }
      } catch (error) {
        this.$modal.msgError('获取产品选项失败：' + error.message);
      }
    },

    // 清除产品选项缓存
    clearProductsCache() {
      localStorage.removeItem('productOptionsData');
    },
  }
};
</script>
